package com.lingjtx.common.other.helper;


import com.lingjtx.common.core.RedisOptions;
import com.lingjtx.common.core.constant.RedisConfig;
import com.lingjtx.common.core.handle.ObjectPool;
import com.lingjtx.common.core.util.StringUtil;
import com.lingjtx.common.other.http.Call;
import com.lingjtx.common.other.http.Network;
import com.lingjtx.common.other.http.RemoteService;
import com.lingjtx.common.other.model.weixin.*;

import java.net.http.HttpClient;
import java.util.Objects;

/**
 * 用于缓存记录第三方token，常用数据字典数据，热点数据
 */
public enum DataCachePool {

    INSTANCE;

    public String getWxAccessToken(RedisOptions redisOptions, ObjectPool<HttpClient> objectPool) {
        String token = (String) redisOptions.get(RedisConfig.KEY_WEI_XIN_ACCESS_TOKEN);
        if (StringUtil.isEmpty(token)) {
            RemoteService service = Network.remote(RemoteService.class, objectPool);
            Call<AccessTokenResponse> call = service.getAccessToken(new AccessTokenRequest());
            AccessTokenResponse result = call.execute();
            if (Objects.nonNull(result) && StringUtil.isNotEmpty(result.getAccess_token())) {
                redisOptions.set(RedisConfig.KEY_WEI_XIN_ACCESS_TOKEN, result.getAccess_token(), result.getExpires_in());
                return result.getAccess_token();
            }
        }
        return token;
    }

    public OauthResponse getWXOauthAccessToken(String code, String state, RedisOptions redisOptions, ObjectPool<HttpClient> objectPool) {
        if (StringUtil.isNotEmpty(code) && StringUtil.isNotEmpty(state)) {
            // state是否是服务器生成的，有效继续
            if (redisOptions.exists(state)) {
                redisOptions.delete(state);
                RemoteService service = Network.remote(RemoteService.class, objectPool);
                Call<OauthResponse> call = service.getOauthAccessToken(new OauthRequest(code));
                OauthResponse result = call.execute();
                if (Objects.nonNull(result)) {
                    return result;
                }
            }
        }
        return null;
    }

    public String getTicket(RedisOptions redis, ObjectPool<HttpClient> objectPool) {
        String ticket = (String) redis.get(RedisConfig.KEY_WEI_XIN_JSAPI_TICKET);
        if (StringUtil.isEmpty(ticket)) {
            String token = DataCachePool.INSTANCE.getWxAccessToken(redis, objectPool);
            RemoteService service = Network.remote(RemoteService.class, objectPool);
            Call<TicketResponse> call = service.getTicket(token, "jsapi");
            TicketResponse result = call.execute();
            if (Objects.nonNull(result) && StringUtil.isNotEmpty(result.getTicket())) {
                redis.set(RedisConfig.KEY_WEI_XIN_JSAPI_TICKET, result.getTicket(), result.getExpires_in());
                return result.getTicket();
            }
        }
        return ticket;
    }
}
